package com.hue.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

/*
    演示hystrix的服务降级
 */
@Service
public class PaymentService {
    public String ok(){
        return "thred："+Thread.currentThread().getName()+",status:ok";
    }

    //配置服务降级，当timeout方法出现异常时调用timeoutHander方法来代替timeout方法
    @HystrixCommand(fallbackMethod = "timeoutHander",
            //配置timeout方法执行时间不能大于3000ms，否则当做异常处理
            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
            })
    public String timeout() throws InterruptedException {
        Thread.sleep(4000);
        return "thread："+Thread.currentThread().getName()+"status:timeout";
    }

    public String timeoutHander(){
        return "thread:"+Thread.currentThread().getName()+"status:服务降级";
    }

    @HystrixCommand(fallbackMethod = "fusingHander",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启短路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//失败率达到多少后开启服务熔断
    })
    public String fusing(int id) {
        //如果id<0抛出异常，发生服务降级
        if(id<0){
            throw new RuntimeException("id不能小于0");
        }
        String code = IdUtil.simpleUUID();
        return "正常运行，流水号:"+code;
    }

    public String fusingHander(int id){
        return "id不能小于0,id="+id;
    }
}
